package com.ecommerce.dal.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.ecommerce.dal.dao.ICustomerDAO;
import com.ecommerce.dal.entity.Client;
import com.ecommerce.dal.entity.Customer;
import com.ecommerce.dal.util.CustomHibernateDAOSupport;

/**
 * always refer to PK as CUSTOMER_ID in HQL clauses.
 * 
 */
@Repository("customerDAO")
public class CustomerDAO extends CustomHibernateDAOSupport implements
		ICustomerDAO {


	@Override
	public void save(Customer customer) {
		getHibernateTemplate().save(customer);

	}

	@Override
	public void update(Customer customer) {
		getHibernateTemplate().update(customer);

	}

	@Override
	public void delete(Customer customer) {
		getHibernateTemplate().delete(customer);

	}

	@Override
	public Customer findByCustomerId(long customerId) {
		List list = getHibernateTemplate().find(
				"select customer from Customer customer where CUSTOMER_ID =?",
				customerId);
		if ((list != null && list.size()>0))
			return ((Customer) list.get(0));
		return null;
	}

	@Override
	public Customer findByCustomerName(String customerUserName) {
		List list = getHibernateTemplate()
				.find("select customer from Customer customer inner join customer.user user where user.userName=?",
						customerUserName);
		return (Customer) ((list != null && list.size()>0) ?  list.get(0) : null) ;
	}

	@Override
	public boolean checkIfClient(long customerId) {
		List list = getHibernateTemplate()
				.find("select count(client) from Customer customer inner join customer.client client where CLIENT_ID = ?",
						customerId);
		return !((Long) (list.get(0))).equals(Long.valueOf(0)) ? true : false;
	}

	@Override
	public boolean checkCustomerId(long customerId) {
		List list = getHibernateTemplate()
				.find("select count(customer) from Customer customer where CUSTOMER_ID = ?",
						customerId);
		return !((Long) (list.get(0))).equals(Long.valueOf(0)) ? true : false;
	}

	@Override
	public List<Customer> findVerifiedCustomers() {
		List list = getHibernateTemplate().find(
				"from Customer customer where customer.verified = true");
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Customer> findNonVerifiedCustomers() {
		List list = getHibernateTemplate().find(
				"from Customer customer where customer.verified = false");
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public boolean isVerified(long customerId) {
		List list = getHibernateTemplate().find(
				"select customer.verified from Customer customer where CUSTOMER_ID = ?",
				customerId);
		if ((list != null && list.size()>0))
			return ((Boolean) (list.get(0))).equals(Boolean.TRUE) ? true : false;
		return false;
	}

}
